import os
from datetime import datetime
from typing import List
import pyqrcode


def crc8_sae_j1850(data: bytes) -> int:
    poly = 0x1D
    crc = 0xFF
    for b in data:
        crc ^= b
        for _ in range(8):
            if crc & 0x80:
                crc = ((crc << 1) ^ poly) & 0xFF
            else:
                crc = (crc << 1) & 0xFF
    crc ^= 0xFF
    return crc


def update_function_code(input_code: str, car_model: str, functions: List[str]) -> str:
    # "小鹿灯", "功放", "记录仪", "盲区检测", "倒车侧向制动",
    # "紧急车道保持", "索尼音效", "微波雷达", "抬头显示",
    # "香氛系统", "方向盘加热", "座椅通风", "前雷达开关",
    # "座椅开关", "北斗+hicar", "逸+8155", "尚360"
    for function in functions:
        if function == "小鹿灯":
            input_code = input_code[:239] + "2" + input_code[240:]
        elif function == "功放":
            input_code = input_code[:82] + "D" + input_code[83:]
        elif function == "记录仪":
            input_code = input_code[:83] + "B" + input_code[84:]
        elif function == "盲区检测":
            if car_model == "瑞虎9":
                input_code = input_code[:121] + "4" + input_code[122:]
                input_code = input_code[:125] + "3" + input_code[126:]
                input_code = input_code[:164] + "6" + input_code[165:]
            elif car_model in ("瑶光", "虎8L"):
                input_code = input_code[:121] + "4" + input_code[122:]
                input_code = input_code[:125] + "3" + input_code[126:]
                input_code = input_code[:164] + "E" + input_code[165:]
                input_code = input_code[:257] + "2" + input_code[258:]
            elif car_model == "瑶光CDM":
                input_code = input_code[:121] + "4" + input_code[122:]
                input_code = input_code[:125] + "3" + input_code[126:]
                input_code = input_code[:164] + "E" + input_code[165:]
            elif car_model == "艾瑞泽8":
                input_code = input_code[:121] + "6" + input_code[122:]
                input_code = input_code[:125] + "3" + input_code[126:]
                input_code = input_code[:164] + "E" + input_code[165:]
            else:
                print(f"{car_model}没有对应的功能{function}")
        elif function == "倒车侧向制动":
            input_code = input_code[:163] + "E" + input_code[164:]
        elif function == "紧急车道保持":
            input_code = input_code[:163] + "F" + input_code[164:]
        elif function == "索尼音效":
            input_code = input_code[:45] + "2" + input_code[46:]
            input_code = input_code[:122] + "1" + input_code[123:]
            input_code = input_code[:134] + "A" + input_code[135:]
        elif function == "微波雷达":
            input_code = input_code[:43] + "3" + input_code[44:]
        elif function == "抬头显示":
            input_code = input_code[:86] + "9" + input_code[87:]
        elif function == "香氛系统":
            input_code = input_code[:100] + "C" + input_code[101:]
        elif function == "方向盘加热":
            input_code = input_code[:149] + "E" + input_code[150:]
        elif function == "座椅通风":
            input_code = input_code[:166] + "F" + input_code[167:]
        elif function == "前雷达开关":
            input_code = input_code[:160] + "6" + input_code[161:]
        elif function == "座椅开关":
            input_code = input_code[:178] + "C" + input_code[119:]
        elif function == "北斗+hicar":
            input_code = input_code[:240] + "4" + input_code[241:]
            input_code = input_code[:245] + "4" + input_code[246:]
        elif function == "逸+8155":
            input_code = input_code[:82] + "8" + input_code[83:]
            input_code = input_code[:240] + "4" + input_code[241:]
            input_code = input_code[:245] + "4" + input_code[246:]
        elif function == "尚360":
            input_code = input_code[:41] + "3" + input_code[42:]
            input_code = input_code[:82] + "8" + input_code[83:]
            input_code = input_code[:87] + "2" + input_code[88:]
        else:
            print(f"{car_model}没有对应的功能{function}")

    return input_code


def generate_qr_code(input_code: str, car_model: str, functions: List[str], pic_file_path) -> str:
    input_code = update_function_code(input_code, car_model, functions)
    byte_code = bytes.fromhex(input_code[:-2])
    result_code = crc8_sae_j1850(byte_code)
    hex_str = str(hex(result_code))[2:]
    if len(hex_str) == 1:
        hex_str = "0" + hex_str

    qr_code_str = input_code[:-2] + hex_str.upper()

    generate_large_qr_code(qr_code_str, pic_file_path)

    return qr_code_str


def generate_large_qr_code(input_code: str, pic_file_path: str):
    # 创建一个QRCode对象
    qr = pyqrcode.create(input_code)

    # 保存二维码为png文件
    qr.png(pic_file_path, scale=6)


def del_old_pic():
    pic_list = sort_files_by_creation("./tmp_pic")
    # print(pic_list[0])
    if len(pic_list) > 10000:
        os.unlink(pic_list[0][0])


def sort_files_by_creation(sorted_dir: str):
    # 获取当前目录下所有文件（排除子目录）
    files = []
    for f in os.listdir(sorted_dir):
        pic_path = os.path.join(sorted_dir, f)
        if os.path.exists(pic_path):
            files.append(pic_path)

    # 附加创建时间并排序
    files_with_time = [(f, os.path.getctime(f)) for f in files]
    print(files_with_time)
    sorted_files = sorted(files_with_time, key=lambda x: x[1])

    # # 格式化输出
    # print(f"{'文件名':<30}{'创建时间':<25}")
    # print("=" * 55)
    # for file, ctime in sorted_files:
    #     print(f"{file:<30}{datetime.fromtimestamp(ctime):%Y-%m-%d %H:%M:%S}")

    return sorted_files


if __name__ == '__main__':
    del_old_pic()

